/**
 * Bestpay.com.cn Inc.
 * Copyright (c) 2011-2018 All Rights Reserved.
 */
package com.sgzn.sgpay.service.support;

import com.sgzn.sgpay.model.request.LoginReqDto;
import com.sgzn.sgpay.model.response.LoginRespDto;
import com.sgzn.sgpay.util.JsonMapperUtil;
import com.sgzn.sgpay.util.httpClient.HttpClientUtil;
import com.sgzn.sgpay.util.httpClient.HttpResultDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpPost;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author zhongzhongyong
 * @version Id: HttpRequestHandler.java, v 0.1 2018/4/7 16:45 zhongzhongyong Exp $$
 */
@Slf4j
@Service
public class HttpRequestHandler {

    /**
     * 调用登录接口【JSON请求格式】获取基础信息OpenId,UnionId
     * @param dto
     * @param initiationID
     * @return 若查得openid则返回；否则返回null
     */
    public LoginRespDto invokeJscode2session(LoginReqDto dto, String initiationID){
        LoginRespDto loginRespDto = new LoginRespDto();
        StringBuffer url = new StringBuffer();
        url.append("https://api.weixin.qq.com/sns/jscode2session?");
        url.append("appid=").append(dto.getAppid()).append("&");
        url.append("secret=").append(dto.getSecret()).append("&");
        url.append("js_code=").append(dto.getJs_code()).append("&");
        url.append("grant_type=").append(dto.getGrant_type());
        log.info("[{}] request url : {}",initiationID,url.toString());
        HttpPost httpPost = new HttpPost(url.toString());//url地址
        //调用并返回结果
        HttpResultDto<String> stringHttpResultDto = HttpClientUtil.sendHttpPostMsg(httpPost);
        String resultStr = stringHttpResultDto.getResult();
        log.info("invokeJscode2session登录接口响应报文 : " + resultStr);
        Map<String,String> resultMap = JsonMapperUtil.stringToBean(resultStr,Map.class);
        if(resultMap.containsKey("openid")){
            log.info("[{}] openid: {} ",initiationID,resultMap.get("openid"));
            loginRespDto.setOpenId(resultMap.get("openid"));
            loginRespDto.setSessionKey(resultMap.get("session_key"));
            loginRespDto.setUnionId(resultMap.get("unionid"));
        }else{
            log.info("[{}] get no openid!",initiationID);
        }
        return loginRespDto;
    }

    //    public static void main(String[] args){
//        SgsLoginRequest request = new SgsLoginRequest();
//        request.setInitiationID("11111111111");
//        System.out.println(getLoginInfo(request));
//    }
}
